<template>
  <div class="container">
    <h1>视频管理</h1>

    <!-- 上传视频部分 -->
    <div class="upload-section">
      <h2>上传视频</h2>
      <form @submit.prevent="uploadVideo" class="upload-form">
        <div class="form-group">
          <label>课程大类：</label>
          <select v-model="uploadForm.categoryId" @change="handleCategoryChange" required>
                   <option value="">请选择课程大类</option>
                   <option v-for="category in categories" :key="category.categoryId" :value="category.categoryId">
                      {{ category.categoryName }}
                   </option>
                </select>
        </div>

        <div class="form-group">
          <label>课程小类：</label>
         <select v-model="uploadForm.subCategoryId" @change="handleSubCategoryChange" required>
               <option value="">请选择课程小类</option>
                <option v-for="subCategory in subCategories" :key="subCategory.categoryId" :value="subCategory.categoryId">
                     {{ subCategory.categoryName }}
               </option>
          </select>
        </div>

        <div class="form-group">
          <label>章节：</label>
          <select v-model="uploadForm.chapterId" @change="handleChapterChange" required>
             <option value="">请选择章节</option>
             <option v-for="chapter in chapters" :key="chapter.chapterId" :value="chapter.chapterId">
                 {{ chapter.chapterName }}
             </option>
           </select>
        </div>

        <div class="form-group">
          <label>具体课程：</label>
          <select v-model="uploadForm.specificCourseId" required>
             <option value="">请选择具体课程</option>
             <option v-for="specificCourse in specificCourses" :key="specificCourse.courseId" :value="specificCourse.courseId">
                  {{ specificCourse.courseName }}
             </option>
            </select>
        </div>

        <div class="form-group">
          <label>视频文件：</label>
          <input type="file" @change="handleFileChange" accept="video/*" ref="fileInputRef" required>
          <div class="selected-files" v-if="uploadForm.file">
            <span class="file-tag">
              {{ uploadForm.file.name }}
              <span class="remove-file" @click="removeFile">x</span>
            </span>
          </div>
          <div v-if="uploadProgress > 0 && uploadProgress < 100" class="upload-progress">
            <div class="progress-bar" :style="{ width: uploadProgress + '%' }"></div>
            <span class="progress-text">{{ uploadProgress }}%</span>
          </div>
        </div>

        <button type="submit" :disabled="isUploading">
          {{ isUploading ? '上传中...' : '上传视频' }}
        </button>
      </form>
    </div>

    <!-- 查看视频部分 -->
    <div class="view-section">
      <h2>查看视频</h2>
      <div class="filter-form">
        <div class="form-group">
          <label>课程大类：</label>
      <select v-model="viewForm.categoryId" @change="handleViewCategoryChange">
      <option value="">请选择课程大类</option>
       <option v-for="category in categories" :key="category.categoryId" :value="category.categoryId">
      {{ category.categoryName }}
    </option>
  </select>
</div>

     <div class="form-group">
  <label>课程小类：</label>
  <select v-model="viewForm.subCategoryId" @change="handleViewSubCategoryChange">
    <option value="">请选择课程小类</option>
    <option v-for="subCategory in viewSubCategories" :key="subCategory.categoryId" :value="subCategory.categoryId">
      {{ subCategory.categoryName }}
    </option>
  </select>
</div>

        <div class="form-group">
  <label>章节：</label>
  <select v-model="viewForm.chapterId" @change="handleViewChapterChange">
    <option value="">请选择章节</option>
    <option v-for="chapter in viewChapters" :key="chapter.chapterId" :value="chapter.chapterId">
      {{ chapter.chapterName }}
    </option>
  </select>
</div>

        <div class="form-group">
  <label>具体课程：</label>
  <select v-model="viewForm.specificCourseId">
    <option value="">请选择具体课程</option>
    <option v-for="specificCourse in viewSpecificCourses" :key="specificCourse.courseId" :value="specificCourse.courseId">
      {{ specificCourse.courseName }}
    </option>
  </select>
</div>

        <button @click="loadVideos" :disabled="isLoading">
          {{ isLoading ? '加载中...' : '查询' }}
        </button>
      </div>

      <div class="video-list" v-if="videos.length > 0">
        <div v-for="video in videos" :key="video.videoId" class="video-item">
          <div class="video-info">
            <h3>{{ video.title }}</h3>
            <p>上传时间：{{ video.createTime }}</p>
            <p>上传人：{{ video.createName }}</p>
            <p>路径：{{ video.categoryName }} > {{ video.subCategoryName }} > {{ video.chapterName }} > {{ video.specificCourseName }}</p>
          </div>
          <div class="video-actions">
            <button @click="playVideo(video)">播放</button>
            <button @click="editVideo(video)">编辑</button>
            <button @click="deleteVideo(video)" class="delete-btn">删除</button>
          </div>
        </div>
      </div>
      <div v-else class="no-videos">
        暂无视频
      </div>
    </div>

    <!-- 课程分类管理模块 -->
    <div class="manage-section">
      <h2>课程分类管理</h2>
      <div class="manage-tabs">
        <button :class="{ active: activeTab === 'category' }" @click="activeTab = 'category'">课程大类</button>
        <button :class="{ active: activeTab === 'subCategory' }" @click="activeTab = 'subCategory'">课程小类</button>
        <button :class="{ active: activeTab === 'chapter' }" @click="activeTab = 'chapter'">章节</button>
        <button :class="{ active: activeTab === 'specificCourse' }" @click="activeTab = 'specificCourse'">具体课程</button>
      </div>

      <!-- 课程大类管理 -->
      <div v-if="activeTab === 'category'" class="manage-content">
        <h3>课程大类列表</h3>
        <div class="add-form-row">
          <input type="text" v-model="newCategoryName" placeholder="新增课程大类名称" />
          <input type="text" v-model="newCategoryImgSrc" placeholder="图片链接（可选）" />
          <button @click="addCategory">新增大类</button>
        </div>
        <ul class="manage-list">
          <li v-for="category in categories" :key="category.categoryId" class="manage-item">
            <span>{{ category.categoryName }}</span>
            <div class="actions">
              <button @click="openEditCategoryDialog(category)">编辑</button>
              <button @click="deleteCategory(category.categoryId)" class="delete-btn">删除</button>
            </div>
          </li>
        </ul>
      </div>

      <!-- 课程小类管理 -->
      <div v-if="activeTab === 'subCategory'" class="manage-content">
        <h3>课程小类列表</h3>
        <div class="add-form-row">
         <select v-model="newSubCategoryForm.categoryId" @change="loadSubCategoriesForManagement" class="small-select">
            <option value="">选择课程大类</option>
            <option v-for="cat in categories" :key="cat.categoryId" :value="cat.categoryId">
              {{ cat.categoryName }}
            </option>
          </select>
          <input type="text" v-model="newSubCategoryForm.courseName" placeholder="新增课程小类名称" />
          <!-- <select v-model="newSubCategoryForm.courseType" class="small-select">
            <option value="">选择课程类型</option>
            <option value="单独课程">单独课程</option>
            <option value="课程">课程</option>
          </select> -->
          <button @click="addSubCategory">新增课程小类</button>
        </div>
        <ul class="manage-list">
          <li v-for="subCategory in subCategories" :key="subCategory.categoryId" class="manage-item">
            <span>{{ subCategory.categoryName }}</span>
            <div class="actions">
              <button @click="openEditSubCategoryDialog(subCategory)">编辑</button>
              <button @click="deleteSubCategory(subCategory)" class="delete-btn">删除</button>
            </div>
          </li>
        </ul>
      </div>

      <!-- 章节管理 -->
      <div v-if="activeTab === 'chapter'" class="manage-content">
        <h3>章节列表</h3>
        <div class="add-form-row">
          <select v-model="newChapterForm.selectedSubCategoryId" @change="loadChaptersForManagement" class="small-select">
            <option value="">选择所属课程小类</option>
            <option v-for="subCategory in subCategories" :key="subCategory.categoryId" :value="subCategory.categoryId">
              {{ subCategory.categoryName }}
            </option>
          </select>
          <input type="text" v-model="newChapterForm.chapterName" placeholder="新增章节名称" />
          <button @click="addChapter">新增章节</button>
        </div>
        <ul class="manage-list">
          <li v-for="chapter in chapters" :key="chapter.chapterId" class="manage-item">
            <span>{{ chapter.chapterName }}</span>
            <div class="actions">
              <button @click="openEditChapterDialog(chapter)">编辑</button>
              <button @click="deleteChapter(chapter)" class="delete-btn">删除</button>
            </div>
          </li>
        </ul>
      </div>

      <!-- 具体课程管理 -->
      <div v-if="activeTab === 'specificCourse'" class="manage-content">
        <h3>具体课程列表</h3>
        <div class="add-form-row">
          <select v-model="newSpecificCourseForm.selectedChapterId" @change="loadSpecificCoursesForManagement" class="small-select">
            <option value="">选择所属章节</option>
            <option v-for="chapter in chapters" :key="chapter.chapterId" :value="chapter.chapterId">
              {{ chapter.chapterName }}
            </option>
          </select>
          <input type="text" v-model="newSpecificCourseForm.courseName" placeholder="新增具体课程名称" />
          <select v-model="newSpecificCourseForm.courseType" class="small-select">
    <option value="">选择课程类型</option>
    <option value="单独课程">单独课程</option>
    <option value="课程">课程</option>
  </select>
  <input v-model="newSpecificCourseForm.price" type="number" placeholder="请输入价格">
  <button @click="addSpecificCourse">新增具体课程</button>
        </div>
        <ul class="manage-list">
          <li v-for="specificCourse in specificCourses" :key="specificCourse.courseId" class="manage-item">
            <span>{{ specificCourse.courseName }}</span>
            <div class="actions">
              <button @click="openEditSpecificCourseDialog(specificCourse)">编辑</button>
              <button @click="deleteSpecificCourse(specificCourse)" class="delete-btn">删除</button>
            </div>
          </li>
        </ul>
      </div>
    </div>

    <!-- 视频播放对话框 -->
    <dialog ref="videoDialog" class="video-dialog">
      <div class="dialog-content">
        <h3>{{ currentVideo?.title }}</h3>
        <div class="video-container">
          <video 
            ref="videoPlayer" 
            controls 
            preload="metadata"
            crossorigin="anonymous"
            class="video-player"
            playsinline
            webkit-playsinline
          >
            <source :src="currentVideo?.link" type="video/mp4">
            您的浏览器不支持视频播放。
          </video>
          <div v-if="videoError" class="video-error">
            {{ videoError }}
            <button v-if="videoError" @click="retryPlayVideo" class="retry-btn">
              重试播放
            </button>
          </div>
        </div>
        <button @click="closeVideoDialog" class="close-btn">关闭</button>
      </div>
    </dialog>

    <!-- 编辑视频标题对话框 -->
    <dialog ref="editDialog" class="edit-dialog">
      <div class="dialog-content">
        <h3>编辑视频标题</h3>
        <input v-model="editForm.title" type="text" placeholder="请输入新的视频标题">
        <div class="dialog-actions">
          <button @click="saveEdit">保存</button>
          <button @click="closeEditDialog" class="cancel-btn">取消</button>
        </div>
      </div>
    </dialog>

    <!-- 编辑课程大类对话框 -->
    <dialog ref="editCategoryDialog" class="edit-dialog">
      <div class="dialog-content">
        <h3>编辑课程大类</h3>
        <input v-model="editCategoryForm.categoryName" type="text" placeholder="请输入课程大类名称">
        <input v-model="editCategoryForm.imgSrc" type="text" placeholder="请输入图片链接（可选）">
        <div class="dialog-actions">
          <button @click="saveCategoryEdit">保存</button>
          <button @click="closeEditCategoryDialog" class="cancel-btn">取消</button>
        </div>
      </div>
    </dialog>

    <!-- 编辑课程小类对话框 -->
    <dialog ref="editSubCategoryDialog" class="edit-dialog">
      <div class="dialog-content">
        <h3>编辑课程小类</h3>
    <input v-model="editSubCategoryForm.categoryName" type="text" placeholder="请输入课程小类名称">
<select v-model="editSubCategoryForm.parentCategoryId" class="small-select">
  <option value="">选择所属课程大类</option>
  <option v-for="cat in categories" :key="cat.categoryId" :value="cat.categoryId">
    {{ cat.categoryName }}
  </option>
</select>
        <div class="dialog-actions">
          <button @click="saveSubCategoryEdit">保存</button>
          <button @click="closeEditSubCategoryDialog" class="cancel-btn">取消</button>
        </div>
      </div>
    </dialog>

    <!-- 编辑章节对话框 -->
    <dialog ref="editChapterDialog" class="edit-dialog">
      <div class="dialog-content">
        <h3>编辑章节</h3>
        <input v-model="editChapterForm.chapterName" type="text" placeholder="请输入章节名称">
        <select v-model="editChapterForm.isFree" class="small-select">
          <option :value="0">非免费</option>
          <option :value="1">免费</option>
        </select>
        <div class="dialog-actions">
          <button @click="saveChapterEdit">保存</button>
          <button @click="closeEditChapterDialog" class="cancel-btn">取消</button>
        </div>
      </div>
    </dialog>

    <!-- 编辑具体课程对话框 -->
    <dialog ref="editSpecificCourseDialog" class="edit-dialog">
      <div class="dialog-content">
        <h3>编辑具体课程</h3>
       <input v-model="editSpecificCourseForm.courseName" type="text" placeholder="请输入具体课程名称">
<select v-model="editSpecificCourseForm.courseType" class="small-select">
  <option value="">选择课程类型</option>
  <option value="单独课程">单独课程</option>
  <option value="课程">课程</option>
</select>
<select v-model="editSpecificCourseForm.chapterId" class="small-select">
  <option value="">选择所属章节</option>
  <option v-for="chapter in chapters" :key="chapter.chapterId" :value="chapter.chapterId">
    {{ chapter.chapterName }}
  </option>
</select>
<input v-model="editSpecificCourseForm.price" type="number" placeholder="请输入价格">
        <div class="dialog-actions">
          <button @click="saveSpecificCourseEdit">保存</button>
          <button @click="closeEditSpecificCourseDialog" class="cancel-btn">取消</button>
        </div>
      </div>
    </dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import axios from 'axios'

const BACKEND_BASE_URL = 'http://192.140.166.207:8088'

// 上传表单数据
const uploadForm = ref({
  categoryId: '',
  subCategoryId: '',
  chapterId: '',
  specificCourseId: '',
  file: null
})

// 查看表单数据
const viewForm = ref({
  categoryId: '',
  subCategoryId: '',
  chapterId: '',
  specificCourseId: ''
})

// 编辑视频表单数据
const editForm = ref({
  videoId: null,
  title: '',
  originalTitle: '',
  fileExtension: ''
})

// 管理模块状态
const activeTab = ref('category')

// 课程大类管理表单
const newCategoryName = ref('')
const newCategoryImgSrc = ref('')
const editCategoryForm = ref({
  categoryId: null,
  categoryName: '',
  imgSrc: ''
})

// 课程小类管理表单
const newSubCategoryForm = ref({
  categoryId: '',
  courseName: '',
  courseType: ''
})
const editSubCategoryForm = ref({
   categoryId: null,         // 小类ID
  categoryName: '',         // 小类名称
  parentCategoryId: ''      // 所属大类ID
})

// 章节管理表单
const newChapterForm = ref({
  selectedSubCategoryId: '',
  chapterName: '',
  isFree: 0
})
const editChapterForm = ref({
  chapterId: null,
  chapterName: '',
  isFree: 0
})

// 具体课程管理表单
const newSpecificCourseForm = ref({
  selectedChapterId: '',
  courseName: '',
  courseType: '',
  price: ''
})
const editSpecificCourseForm = ref({
  courseId: null,
  courseName: '',
  chapterId: '',
  courseType: '',
  price: ''
  
})

// 状态数据
const categories = ref([])
const subCategories = ref([])
const chapters = ref([])
const specificCourses = ref([])
const viewSubCategories = ref([])
const viewChapters = ref([])
const viewSpecificCourses = ref([])
const videos = ref([])
const isUploading = ref(false)
const isLoading = ref(false)
const currentVideo = ref(null)
const uploadProgress = ref(0)
const videoError = ref('')

// 对话框引用
const videoDialog = ref(null)
const editDialog = ref(null)
const videoPlayer = ref(null)
const fileInputRef = ref(null)
const editCategoryDialog = ref(null)
const editSubCategoryDialog = ref(null)
const editChapterDialog = ref(null)
const editSpecificCourseDialog = ref(null)

// --- 加载数据相关函数 ---

// 加载课程大类
const loadCategories = async () => {
  try {
    const response = await axios.get(`${BACKEND_BASE_URL}/api/course-hierarchy/categories`)
    if (response.data.code === 200) {
      categories.value = response.data.data
    } else {
      categories.value = []
      alert(`加载课程大类失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    alert('加载课程大类请求失败，请重试')
    categories.value = []
  }
}

// 加载课程小类
const loadSubCategories = async (categoryId) => {
  subCategories.value = []
  if (!categoryId) return
  const response = await axios.get(`${BACKEND_BASE_URL}/api/course-hierarchy/categories/${categoryId}/subcategories`)
  if (response.data.code === 200) {
    subCategories.value = response.data.data
  }
}

// 加载章节
const loadChapters = async (subCategoryId) => {
  chapters.value = []
  if (!subCategoryId) return

  try {
    const response = await axios.get(`${BACKEND_BASE_URL}/api/course-hierarchy/subcategories/${subCategoryId}/chapters`)
    if (response.data.code === 200) {
      chapters.value = response.data.data
    } else {
      chapters.value = []
      alert(`加载章节失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    alert('加载章节请求失败，请重试')
    chapters.value = []
  }
}

// 加载具体课程
// 加载具体课程
const loadSpecificCourses = async (chapterId) => {
  specificCourses.value = []
  if (!chapterId) return

  try {
    const response = await axios.get(`${BACKEND_BASE_URL}/api/course-hierarchy/chapters/${chapterId}/courses`)
    if (response.data.code === 200) {
      specificCourses.value = response.data.data
    } else {
      specificCourses.value = []
      alert(`加载具体课程失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    alert('加载具体课程请求失败，请重试')
    specificCourses.value = []
  }
}

// 加载查看部分的课程小类
const loadViewSubCategories = async (categoryId) => {
  viewSubCategories.value = []
  if (!categoryId) return

  try {
    const response = await axios.get(`${BACKEND_BASE_URL}/api/course-hierarchy/categories/${categoryId}/subcategories`)
    if (response.data.code === 200) {
      viewSubCategories.value = response.data.data
    } else {
      viewSubCategories.value = []
      alert(`加载课程小类失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    alert('加载课程小类请求失败，请重试')
    viewSubCategories.value = []
  }
}


// 加载查看部分的章节
const loadViewChapters = async (subCategoryId) => {
  viewChapters.value = []
  if (!subCategoryId) return

  try {
    const response = await axios.get(`${BACKEND_BASE_URL}/api/course-hierarchy/subcategories/${subCategoryId}/chapters`)
    if (response.data.code === 200) {
      viewChapters.value = response.data.data
    } else {
      viewChapters.value = []
      alert(`加载章节失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    alert('加载章节请求失败，请重试')
    viewChapters.value = []
  }
}


// 加载查看部分的具体课程
const loadViewSpecificCourses = async (chapterId) => {
  viewSpecificCourses.value = []
  if (!chapterId) return

  try {
    const response = await axios.get(`${BACKEND_BASE_URL}/api/course-hierarchy/chapters/${chapterId}/courses`)
    if (response.data.code === 200) {
      viewSpecificCourses.value = response.data.data
    } else {
      viewSpecificCourses.value = []
      alert(`加载具体课程失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    alert('加载具体课程请求失败，请重试')
    viewSpecificCourses.value = []
  }
}

// --- 表单事件处理 ---

// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0]
  if (file) {
    uploadForm.value.file = file
  }
}

// 移除文件
const removeFile = () => {
  uploadForm.value.file = null
  if (fileInputRef.value) {
    fileInputRef.value.value = ''
  }
}

// 处理上传部分的课程大类变化
const handleCategoryChange = () => {
  uploadForm.value.subCategoryId = ''
  uploadForm.value.chapterId = ''
  uploadForm.value.specificCourseId = ''
  loadSubCategories(uploadForm.value.categoryId)
}

// 处理上传部分的课程小类变化
const handleSubCategoryChange = () => {
  uploadForm.value.chapterId = ''
  uploadForm.value.specificCourseId = ''
  loadChapters(uploadForm.value.subCategoryId)
}

// 处理上传部分的章节变化
const handleChapterChange = () => {
  uploadForm.value.specificCourseId = ''
  loadSpecificCourses(uploadForm.value.chapterId)
}

// 处理查看部分的课程大类变化
const handleViewCategoryChange = () => {
  viewForm.value.subCategoryId = ''
  viewForm.value.chapterId = ''
  viewForm.value.specificCourseId = ''
  loadViewSubCategories(viewForm.value.categoryId)
}


// 处理查看部分的课程小类变化
const handleViewSubCategoryChange = () => {
  viewForm.value.chapterId = ''
  viewForm.value.specificCourseId = ''
  loadViewChapters(viewForm.value.subCategoryId)
}

// 处理查看部分的章节变化
const handleViewChapterChange = () => {
  viewForm.value.specificCourseId = ''
  loadViewSpecificCourses(viewForm.value.chapterId)
}
// --- 视频上传/播放/编辑/删除 ---

// 上传视频
const uploadVideo = async () => {
  if (!uploadForm.value.file) {
    alert('请选择要上传的视频文件')
    return
  }
  if (!uploadForm.value.categoryId || !uploadForm.value.subCategoryId || !uploadForm.value.chapterId || !uploadForm.value.specificCourseId) {
    alert('请完整选择课程层级')
    return
  }
  isUploading.value = true
  uploadProgress.value = 0
  const formData = new FormData()
  formData.append('file', uploadForm.value.file)
  formData.append('createName', localStorage.getItem('username') || '未知用户')

  try {
    // 使用正确的接口路径，将四个ID作为路径参数
    const response = await axios.post(
      `${BACKEND_BASE_URL}/api/video/upload/${uploadForm.value.categoryId}/${uploadForm.value.subCategoryId}/${uploadForm.value.chapterId}/${uploadForm.value.specificCourseId}`, 
      formData, 
      {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: (progressEvent) => {
          uploadProgress.value = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        }
      }
    )
    if (response.data.code === 200) {
      alert('视频上传成功')
      // 重置表单
      uploadForm.value.file = null
      uploadForm.value.categoryId = ''
      uploadForm.value.subCategoryId = ''
      uploadForm.value.chapterId = ''
      uploadForm.value.specificCourseId = ''
      if (fileInputRef.value) fileInputRef.value.value = ''
      uploadProgress.value = 0
      loadVideos()
    } else {
      alert(`上传失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    console.error('上传视频失败:', error)
    alert('上传视频失败，请重试')
  } finally {
    isUploading.value = false
    uploadProgress.value = 0
  }
}

// 加载视频列表
const loadVideos = async () => {
  if (!viewForm.value.categoryId) {
    videos.value = []
    return
  }
  isLoading.value = true
  
  try {
    let url = `${BACKEND_BASE_URL}/api/video/category/${viewForm.value.categoryId}`
    if (viewForm.value.subCategoryId) {
      url = `${BACKEND_BASE_URL}/api/video/subcategory/${viewForm.value.subCategoryId}`
    }
    if (viewForm.value.chapterId) {
      url = `${BACKEND_BASE_URL}/api/video/chapter/${viewForm.value.chapterId}`
    }
    if (viewForm.value.specificCourseId) {
      url = `${BACKEND_BASE_URL}/api/video/course/${viewForm.value.specificCourseId}`
    }

    const response = await axios.get(url)
    if (response.data.code === 200) {
      videos.value = response.data.data
    } else {
      videos.value = []
      alert(`加载视频列表失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    console.error('加载视频列表失败:', error)
    alert('加载视频列表失败，请重试')
    videos.value = []
  } finally {
    isLoading.value = false
  }
}

// 播放视频
const playVideo = (video) => {
  if (!video || !video.link) {
    alert('视频信息不完整，无法播放')
    return
  }
  currentVideo.value = video
  videoDialog.value.showModal()
  nextTick(() => {
    if (videoPlayer.value && currentVideo.value?.link) {
      const videoUrl = currentVideo.value.link
      videoError.value = ''
      if (!videoUrl.startsWith('http')) {
        videoError.value = '视频URL格式不正确'
        return
      }
      videoPlayer.value.pause()
      videoPlayer.value.removeAttribute('src')
      videoPlayer.value.load()
      videoPlayer.value.src = videoUrl
      videoPlayer.value.onerror = (e) => {
        console.error("视频播放错误:", e, videoPlayer.value.error)
        if (videoPlayer.value.error) {
          switch (videoPlayer.value.error.code) {
            case 1:
              videoError.value = '视频加载被中断'
              break
            case 2:
              videoError.value = '网络错误，请检查网络连接'
              break
            case 3:
              videoError.value = '视频解码错误，请检查视频格式'
              break
            case 4:
              videoError.value = '视频格式不支持或URL无效'
              break
            default:
              videoError.value = '视频加载失败，请稍后重试'
          }
        } else {
          videoError.value = '视频加载失败，未知错误'
        }
      }
      videoPlayer.value.onloadeddata = () => {
        videoError.value = ''
      }
      videoPlayer.value.onwaiting = () => {
        videoError.value = '视频加载中...'
      }
      videoPlayer.value.onstalled = () => {
        videoError.value = '视频播放停滞，请检查网络连接'
      }
      videoPlayer.value.onloadedmetadata = () => {}
      videoPlayer.value.onloadstart = () => {}
      try {
        videoPlayer.value.load()
        const playPromise = videoPlayer.value.play()
        if (playPromise !== undefined) {
          playPromise.catch(e => {
            videoError.value = '视频自动播放失败，请点击播放按钮'
          })
        }
      } catch (error) {
        videoError.value = '视频加载失败，请刷新页面重试'
      }
    } else {
      videoError.value = '视频播放器未就绪或视频链接无效'
    }
  })
}

// 重试播放
const retryPlayVideo = () => {
  if (currentVideo.value) {
    playVideo(currentVideo.value)
  }
}

// 关闭视频对话框
const closeVideoDialog = () => {
  if (videoPlayer.value) {
    try {
      videoPlayer.value.pause()
      videoPlayer.value.removeAttribute('src')
      videoPlayer.value.load()
    } catch (error) {
      console.error("关闭视频对话框时出错:", error)
    }
  }
  videoDialog.value.close()
  currentVideo.value = null
  videoError.value = ''
}

// 编辑视频
const editVideo = (video) => {
  editForm.value = {
    videoId: video.videoId,
    originalTitle: video.title,
    fileExtension: video.title.split('.').pop(),
    title: video.title.substring(0, video.title.lastIndexOf('.'))
  }
  editDialog.value.showModal()
}

// 保存编辑
const saveEdit = async () => {
  if (!editForm.value.title.trim()) {
    alert('请输入视频标题')
    return
  }
  const newFullTitle = editForm.value.title + (editForm.value.fileExtension ? '.' + editForm.value.fileExtension : '')
  try {
    const response = await axios.put(
      `${BACKEND_BASE_URL}/api/video/${editForm.value.videoId}/title`,
      { title: newFullTitle }
    )
    if (response.data.code === 200) {
      alert('修改成功')
      closeEditDialog()
      loadVideos()
    } else {
      alert(`修改失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    alert('修改视频标题失败，请重试')
  }
}

// 关闭编辑对话框
const closeEditDialog = () => {
  editDialog.value.close()
  editForm.value = {
    videoId: null,
    title: '',
    originalTitle: '',
    fileExtension: ''
  }
}

// 删除视频
const deleteVideo = async (video) => {
  if (!confirm('确定要删除这个视频吗？')) {
    return
  }
  try {
    const encodedFileName = encodeURIComponent(video.fileName)
    const response = await axios.delete(`${BACKEND_BASE_URL}/api/video/delete?fileName=${encodedFileName}`)
    if (response.data.code === 200) {
      alert('删除成功')
      loadVideos()
    } else {
      alert(`删除失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    alert('删除视频失败，请重试')
  }
}

// --- 课程大类、课程小类、章节、具体课程管理相关函数 ---

// 新增课程大类
const addCategory = async () => {
  if (!newCategoryName.value.trim()) {
    alert('课程大类名称不能为空')
    return
  }
  const createName = localStorage.getItem('username') || '未知用户'
  const response = await axios.post(`${BACKEND_BASE_URL}/course`, {
    categoryName: newCategoryName.value,
    imgSrc: newCategoryImgSrc.value || null,
    createName
  })
  if (response.data.code === 200) {
    alert('课程大类新增成功')
    newCategoryName.value = ''
    newCategoryImgSrc.value = ''
    await loadCategories()
  } else {
    alert(`新增失败: ${response.data.msg || '未知错误'}`)
  }
}


// 打开编辑课程大类对话框
const openEditCategoryDialog = (category) => {
  editCategoryForm.value = { ...category }
  editCategoryDialog.value.showModal()
}

// 保存编辑后的课程大类
const saveCategoryEdit = async () => {
  if (!editCategoryForm.value.categoryName.trim()) {
    alert('课程大类名称不能为空')
    return
  }
  const amendName = localStorage.getItem('username') || '未知用户'
  const response = await axios.put(
    `${BACKEND_BASE_URL}/course/${editCategoryForm.value.categoryId}`,
    {
      categoryName: editCategoryForm.value.categoryName,
      imgSrc: editCategoryForm.value.imgSrc || null,
      amendName
    }
  )
  if (response.data.code === 200) {
    alert('课程大类修改成功')
    closeEditCategoryDialog()
    await loadCategories()
  } else {
    alert(`修改失败: ${response.data.msg || '未知错误'}`)
  }
}

// 关闭编辑课程大类对话框
const closeEditCategoryDialog = () => {
  editCategoryDialog.value.close()
  editCategoryForm.value = { categoryId: null, categoryName: '', imgSrc: '' }
}

// 删除课程大类
const deleteCategory = async (id) => {
  if (!confirm('确定要删除这个课程大类吗？')) return
  const response = await axios.delete(`${BACKEND_BASE_URL}/course/${id}`)
  if (response.data.code === 200) {
    alert('课程大类删除成功')
    await loadCategories()
  } else {
    alert(`删除失败: ${response.data.msg || '未知错误'}`)
  }
}

// 新增课程小类
const addSubCategory = async () => {
  if (!newSubCategoryForm.value.categoryId) {
    alert('请选择所属课程大类')
    return
  }
  if (!newSubCategoryForm.value.courseName.trim()) {
    alert('课程小类名称不能为空')
    return
  }
  const createName = localStorage.getItem('username') || '未知用户'
  const response = await axios.post(
    `${BACKEND_BASE_URL}/api/course-hierarchy/categories/${newSubCategoryForm.value.categoryId}/subcategories`,
    {
      categoryName: newSubCategoryForm.value.courseName,
      createName
    }
  )
  if (response.data.code === 200) {
    alert('课程小类新增成功')
    newSubCategoryForm.value.courseName = ''
    newSubCategoryForm.value.categoryId = ''
    await loadSubCategoriesForManagement()
  } else {
    alert(`新增失败: ${response.data.msg || '未知错误'}`)
  }
}

// 加载课程小类列表 (用于管理tab)
const loadSubCategoriesForManagement = async () => {
  if (!newSubCategoryForm.value.categoryId) {
    subCategories.value = []
    return
  }
  try {
    const response = await axios.get(`${BACKEND_BASE_URL}/api/course-hierarchy/categories/${newSubCategoryForm.value.categoryId}/subcategories`)
    if (response.data.code === 200) {
      subCategories.value = response.data.data
    } else {
      subCategories.value = []
      alert(`加载课程小类失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    alert('加载课程小类请求失败，请重试')
    subCategories.value = []
  }
}

// 打开编辑课程小类对话框
const openEditSubCategoryDialog = (subCategory) => {
  editSubCategoryForm.value = {
    categoryId: subCategory.categoryId,
    categoryName: subCategory.categoryName,
    parentCategoryId: subCategory.parentCategoryId
  }
  editSubCategoryDialog.value.showModal()
}
// 保存编辑后的课程小类
const saveSubCategoryEdit = async () => {
  if (!editSubCategoryForm.value.categoryName.trim()) {
    alert('课程小类名称不能为空')
    return
  }
  if (!editSubCategoryForm.value.parentCategoryId) {
    alert('请选择所属课程大类')
    return
  }
  const amendName = localStorage.getItem('username') || '未知用户'
  const response = await axios.put(
    `${BACKEND_BASE_URL}/api/course-hierarchy/subcategories/${editSubCategoryForm.value.categoryId}`,
    {
      categoryName: editSubCategoryForm.value.categoryName,
      parentCategoryId: editSubCategoryForm.value.parentCategoryId,
      amendName
    }
  )
  if (response.data.code === 200) {
    alert('课程小类修改成功')
    const parentId = editSubCategoryForm.value.parentCategoryId
    closeEditSubCategoryDialog()
    await loadSubCategoriesForManagement(parentId)
  } else {
    alert(`修改失败: ${response.data.msg || '未知错误'}`)
  }
}

// 关闭编辑课程小类对话框
const closeEditSubCategoryDialog = () => {
  editSubCategoryDialog.value.close()
  editSubCategoryForm.value = { categoryId: null, categoryName: '', parentCategoryId: '' }
}

// 删除课程小类
const deleteSubCategory = async (subCategory) => {
  if (!confirm(`确定要删除课程小类"${subCategory.categoryName}"吗？`)) {
    return
  }
  try {
    const response = await axios.delete(`${BACKEND_BASE_URL}/api/course-hierarchy/subcategories/${subCategory.categoryId}`)
    if (response.data.code === 200) {
      alert('删除成功')
      await loadSubCategoriesForManagement()
    } else {
      alert(`删除失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    alert('删除失败，请重试')
  }
}
// 新增章节
const addChapter = async () => {
  if (!newChapterForm.value.selectedSubCategoryId) {
    alert('请选择所属课程小类')
    return
  }
  if (!newChapterForm.value.chapterName.trim()) {
    alert('章节名称不能为空')
    return
  }
  const createName = localStorage.getItem('username') || '未知用户'
  const response = await axios.post(
    `${BACKEND_BASE_URL}/api/course-hierarchy/subcategories/${newChapterForm.value.selectedSubCategoryId}/chapters`,
    {
      chapterName: newChapterForm.value.chapterName,
      isFree: newChapterForm.value.isFree,
      createName
    }
  )
  if (response.data.code === 200) {
    alert('章节新增成功')
    newChapterForm.value.chapterName = ''
    // newChapterForm.value.selectedSubCategoryId = ''
    await loadChaptersForManagement()
  } else {
    alert(`新增失败: ${response.data.msg || '未知错误'}`)
  }
}

// 加载章节列表 (用于管理tab)
const loadChaptersForManagement = async () => {
  if (!newChapterForm.value.selectedSubCategoryId) {
    chapters.value = []
    return
  }
  try {
    const response = await axios.get(`${BACKEND_BASE_URL}/api/course-hierarchy/subcategories/${newChapterForm.value.selectedSubCategoryId}/chapters`)
    if (response.data.code === 200) {
      chapters.value = response.data.data
    } else {
      chapters.value = []
      alert(`加载章节失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    alert('加载章节请求失败，请重试')
    chapters.value = []
  }
}

// 新增具体课程
const addSpecificCourse = async () => {
  if (!newSpecificCourseForm.value.selectedChapterId) {
    alert('请选择所属章节')
    return
  }
  if (!newSpecificCourseForm.value.courseName.trim()) {
    alert('具体课程名称不能为空')
    return
  }
  if (!newSpecificCourseForm.value.courseType) {
    alert('请选择课程类型')
    return
  }
  const createName = localStorage.getItem('username') || '未知用户'
  // const teacherId = Number(localStorage.getItem('teacher_id'))
  const teacherId = JSON.parse(localStorage.getItem('token')).teacherId
  console.log('teacherId to send:', teacherId, typeof teacherId)
  const response = await axios.post(
    `${BACKEND_BASE_URL}/api/course-hierarchy/chapters/${newSpecificCourseForm.value.selectedChapterId}/courses`,
    {
      courseName: newSpecificCourseForm.value.courseName,
      courseType: newSpecificCourseForm.value.courseType,
      price: newSpecificCourseForm.value.price,
      createName,
      teacherId // 新增
    }
  )
  if (response.data.code === 200) {
    alert('具体课程新增成功')
    newSpecificCourseForm.value.courseName = ''
    await loadSpecificCoursesForManagement()
  } else {
    alert(`新增失败: ${response.data.msg || '未知错误'}`)
  }
}


// 加载具体课程列表 (用于管理tab)
const loadSpecificCoursesForManagement = async () => {
  if (!newSpecificCourseForm.value.selectedChapterId) {
    specificCourses.value = []
    return
  }
  try {
    const response = await axios.get(`${BACKEND_BASE_URL}/api/course-hierarchy/chapters/${newSpecificCourseForm.value.selectedChapterId}/courses`)
    if (response.data.code === 200) {
      specificCourses.value = response.data.data
    } else {
      specificCourses.value = []
      alert(`加载具体课程失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    alert('加载具体课程请求失败，请重试')
    specificCourses.value = []
  }
}
// 打开编辑章节对话框
const openEditChapterDialog = (chapter) => {
  editChapterForm.value = { ...chapter }
  editChapterDialog.value.showModal()
}

// 保存编辑后的章节
const saveChapterEdit = async () => {
  if (!editChapterForm.value.chapterName.trim()) {
    alert('章节名称不能为空')
    return
  }
  const amendName = localStorage.getItem('username') || '未知用户'
  const response = await axios.put(
    `${BACKEND_BASE_URL}/api/course-hierarchy/chapters/${editChapterForm.value.chapterId}`,
    {
      chapterName: editChapterForm.value.chapterName,
      isFree: editChapterForm.value.isFree,
      amendName
    }
  )
  if (response.data.code === 200) {
    alert('章节修改成功')
    closeEditChapterDialog()
    await loadChaptersForManagement()
  } else {
    alert(`修改失败: ${response.data.msg || '未知错误'}`)
  }
}

// 关闭编辑章节对话框
const closeEditChapterDialog = () => {
  editChapterDialog.value.close()
  editChapterForm.value = { chapterId: null, chapterName: '', isFree: 0 }
}

// 删除章节
const deleteChapter = async (chapter) => {
  if (!confirm(`确定要删除章节"${chapter.chapterName}"吗？`)) {
    return
  }
  try {
    const response = await axios.delete(`${BACKEND_BASE_URL}/api/course-hierarchy/chapters/${chapter.chapterId}`)
    if (response.data.code === 200) {
      alert('删除成功')
      await loadChaptersForManagement()
    } else {
      alert(`删除失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    alert('删除失败，请重试')
  }
}

// 打开编辑具体课程对话框
const openEditSpecificCourseDialog = (specificCourse) => {
  editSpecificCourseForm.value = {
    courseId: specificCourse.courseId,
    courseName: specificCourse.courseName,
    courseType: specificCourse.courseType,
    price: specificCourse.price
  }
  editSpecificCourseDialog.value.showModal()
}

// 保存编辑后的具体课程
const saveSpecificCourseEdit = async () => {
  if (!editSpecificCourseForm.value.courseName.trim()) {
    alert('具体课程名称不能为空')
    return
  }
  if (!editSpecificCourseForm.value.chapterId) {
    alert('请选择所属章节')
    return
  }
   if (!editSpecificCourseForm.value.price) {
    alert('请输入价格')
    return
  }
  const amendName = localStorage.getItem('username') || '未知用户'
  const response = await axios.put(
    `${BACKEND_BASE_URL}/api/course-hierarchy/courses/${editSpecificCourseForm.value.courseId}`,
    {
      courseName: editSpecificCourseForm.value.courseName,
      chapterId: editSpecificCourseForm.value.chapterId,
      courseType: editSpecificCourseForm.value.courseType,
      price: editSpecificCourseForm.value.price, 
      amendName
    }
  )
  if (response.data.code === 200) {
    alert('具体课程修改成功')
    closeEditSpecificCourseDialog()
    await loadSpecificCoursesForManagement()
  } else {
    alert(`修改失败: ${response.data.msg || '未知错误'}`)
  }
}

// 关闭编辑具体课程对话框
const closeEditSpecificCourseDialog = () => {
  editSpecificCourseDialog.value.close()
  editSpecificCourseForm.value = { courseId: null, courseName: '', chapterId: '' }
}

// 删除具体课程
const deleteSpecificCourse = async (course) => {
  if (!confirm(`确定要删除具体课程"${course.courseName}"吗？`)) {
    return
  }
  try {
    const response = await axios.delete(`${BACKEND_BASE_URL}/api/course-hierarchy/courses/${course.courseId}`)
    if (response.data.code === 200) {
      alert('删除成功')
      await loadSpecificCoursesForManagement()
    } else {
      alert(`删除失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    alert('删除失败，请重试')
  }
}

// --- 联动刷新函数 ---

const refreshAllCategoryData = async () => {
  await loadCategories()
  if (uploadForm.value.categoryName) {
    await loadSubCategories(uploadForm.value.categoryName)
    if (uploadForm.value.subCategoryName) {
      const selectedSubCategory = subCategories.value.find(c => c.categoryName === uploadForm.value.subCategoryName)
      if (selectedSubCategory) {
        await loadChapters(selectedSubCategory.categoryName)
        if (uploadForm.value.chapterName) {
          const selectedChapter = chapters.value.find(c => c.chapterName === uploadForm.value.chapterName)
          if (selectedChapter) {
            await loadSpecificCourses(selectedChapter.chapterName)
          }
        }
      }
    }
  }
  if (viewForm.value.categoryName) {
    await loadViewSubCategories(viewForm.value.categoryName)
    if (viewForm.value.subCategoryName) {
      const selectedSubCategory = viewSubCategories.value.find(c => c.categoryName === viewForm.value.subCategoryName)
      if (selectedSubCategory) {
        await loadViewChapters(selectedSubCategory.categoryName)
        if (viewForm.value.chapterName) {
          const selectedChapter = viewChapters.value.find(c => c.chapterName === viewForm.value.chapterName)
          if (selectedChapter) {
            await loadViewSpecificCourses(selectedChapter.chapterName)
          }
        }
      }
    }
  }
}

const refreshAllSubCategoryData = async () => {
  if (uploadForm.value.categoryName) {
    await loadSubCategories(uploadForm.value.categoryName)
    if (uploadForm.value.subCategoryName) {
      const selectedSubCategory = subCategories.value.find(c => c.categoryName === uploadForm.value.subCategoryName)
      if (selectedSubCategory) {
        await loadChapters(selectedSubCategory.categoryName)
        if (uploadForm.value.chapterName) {
          const selectedChapter = chapters.value.find(c => c.chapterName === uploadForm.value.chapterName)
          if (selectedChapter) {
            await loadSpecificCourses(selectedChapter.chapterName)
          }
        }
      }
    }
  }
  if (viewForm.value.categoryName) {
    await loadViewSubCategories(viewForm.value.categoryName)
    if (viewForm.value.subCategoryName) {
      const selectedSubCategory = viewSubCategories.value.find(c => c.categoryName === viewForm.value.subCategoryName)
      if (selectedSubCategory) {
        await loadViewChapters(selectedSubCategory.categoryName)
        if (viewForm.value.chapterName) {
          const selectedChapter = viewChapters.value.find(c => c.chapterName === viewForm.value.chapterName)
          if (selectedChapter) {
            await loadViewSpecificCourses(selectedChapter.chapterName)
          }
        }
      }
    }
  }
}

const refreshAllChapterData = async () => {
  if (uploadForm.value.subCategoryName) {
    const selectedSubCategory = subCategories.value.find(c => c.categoryName === uploadForm.value.subCategoryName)
    if (selectedSubCategory) {
      await loadChapters(selectedSubCategory.categoryName)
      if (uploadForm.value.chapterName) {
        const selectedChapter = chapters.value.find(c => c.chapterName === uploadForm.value.chapterName)
        if (selectedChapter) {
          await loadSpecificCourses(selectedChapter.chapterName)
        }
      }
    }
  }
  if (viewForm.value.subCategoryName) {
    const selectedSubCategory = viewSubCategories.value.find(c => c.categoryName === viewForm.value.subCategoryName)
    if (selectedSubCategory) {
      await loadViewChapters(selectedSubCategory.categoryName)
      if (viewForm.value.chapterName) {
        const selectedChapter = viewChapters.value.find(c => c.chapterName === viewForm.value.chapterName)
        if (selectedChapter) {
          await loadViewSpecificCourses(selectedChapter.chapterName)
        }
      }
    }
  }
}

const refreshAllSpecificCourseData = async () => {
  if (uploadForm.value.chapterName) {
    const selectedChapter = chapters.value.find(c => c.chapterName === uploadForm.value.chapterName)
    if (selectedChapter) {
      await loadSpecificCourses(selectedChapter.chapterName)
    }
  }
  if (viewForm.value.chapterName) {
    const selectedChapter = viewChapters.value.find(c => c.chapterName === viewForm.value.chapterName)
    if (selectedChapter) {
      await loadViewSpecificCourses(selectedChapter.chapterName)
    }
  }
  
}

// 页面加载时获取课程大类
onMounted(() => {
  loadCategories()
})

</script>

<style scoped>
/* 样式同上，直接粘贴即可 */
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}
h1 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}
.upload-section,
.view-section,
.manage-section {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
h2 {
  margin-bottom: 20px;
  color: #333;
  font-size: 1.5em;
}
h3 {
  color: #4CAF50;
  margin-bottom: 15px;
  font-size: 1.2em;
  border-bottom: 2px solid #e0e0e0;
  padding-bottom: 5px;
}
.form-group {
  margin-bottom: 15px;
}
label {
  display: inline-block;
  width: 100px;
  margin-right: 10px;
  color: #666;
}
select,
input[type="file"],
input[type="text"] {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 200px;
  font-size: 14px;
}
.small-select {
  width: 150px;
}
select:focus,
input[type="text"]:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}
button {
  background: #4CAF50;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 10px;
  font-size: 14px;
  transition: background-color 0.3s;
}
button:disabled {
  background: #cccccc;
  cursor: not-allowed;
}
button:hover:not(:disabled) {
  background: #45a049;
}
.delete-btn {
  background: #f44336;
}
.delete-btn:hover:not(:disabled) {
  background: #d32f2f;
}
.cancel-btn {
  background: #9e9e9e;
}
.cancel-btn:hover:not(:disabled) {
  background: #757575;
}
.video-list {
  margin-top: 20px;
}
.video-item {
  background: white;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}
.video-item:hover {
  transform: translateY(-2px);
}
.video-info h3 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 1.1em;
}
.video-info p {
  margin: 5px 0;
  color: #666;
  font-size: 0.9em;
}
.video-actions button {
  margin-left: 10px;
  padding: 8px 15px;
}
.video-dialog,
.edit-dialog {
  padding: 20px;
  border-radius: 8px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  max-width: 800px;
  width: 90%;
}
.dialog-content {
  text-align: center;
}
.dialog-content h3 {
  margin-bottom: 20px;
  color: #333;
}
.video-container {
  position: relative;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  background: #000;
  border-radius: 4px;
  overflow: hidden;
  min-height: 200px;
}
.video-player {
  width: 100%;
  max-height: 70vh;
  display: block;
  background: #000;
}
.video-error {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 15px 25px;
  border-radius: 4px;
  text-align: center;
  z-index: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
  align-items: center;
}
.retry-btn {
  background: #4CAF50;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}
.retry-btn:hover {
  background: #45a049;
}
.close-btn {
  margin-top: 20px;
  background: #666;
}
.close-btn:hover {
  background: #555;
}
.dialog-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 10px;
}
.no-videos {
  text-align: center;
  color: #666;
  padding: 20px;
  font-size: 1.1em;
}
.filter-form {
  display: flex;
  gap: 15px;
  align-items: flex-end;
  margin-bottom: 20px;
  flex-wrap: wrap;
}
.filter-form .form-group {
  margin-bottom: 0;
}
.selected-files {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.file-tag {
  background-color: #e0e0e0;
  padding: 5px 10px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  font-size: 0.9em;
  color: #333;
}
.remove-file {
  margin-left: 8px;
  cursor: pointer;
  color: #666;
  font-weight: bold;
  transition: color 0.2s;
}
.remove-file:hover {
  color: #f44336;
}
.upload-progress {
  margin-top: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
  height: 20px;
}
.progress-bar {
  background-color: #4CAF50;
  height: 100%;
  transition: width 0.3s ease;
}
.progress-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #333;
  font-size: 12px;
  font-weight: bold;
}

/* --- 新增管理模块样式 --- */
.manage-section {
  padding: 20px;
}
.manage-tabs {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 2px solid #eee;
}
.manage-tabs button {
  background: #f0f0f0;
  color: #555;
  border: none;
  padding: 10px 15px;
  cursor: pointer;
  border-radius: 5px 5px 0 0;
  margin-right: 5px;
  transition: background-color 0.3s, color 0.3s;
}
.manage-tabs button.active {
  background: #4CAF50;
  color: white;
  border-bottom: 2px solid #4CAF50;
}
.manage-content {
  background: white;
  padding: 20px;
  border-radius: 0 0 8px 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
.add-form-row {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
  flex-wrap: wrap;
}
.add-form-row input,
.add-form-row select {
  flex-grow: 1;
  min-width: 150px;
}
.add-form-row button {
  margin-right: 0;
}
.manage-list {
  list-style: none;
  padding: 0;
}
.manage-item {
  background: #f9f9f9;
  border: 1px solid #eee;
  padding: 10px 15px;
  margin-bottom: 8px;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.manage-item .actions button {
  padding: 5px 10px;
  font-size: 0.9em;
  margin-left: 8px;
}

@media (max-width: 768px) {
  .container {
    padding: 10px;
  }
  .filter-form {
    flex-direction: column;
    align-items: stretch;
  }
  .filter-form .form-group {
    margin-bottom: 10px;
  }
  .video-item {
    flex-direction: column;
    text-align: center;
  }
  .video-actions {
    margin-top: 10px;
  }
  .video-actions button {
    margin: 5px;
  }
  select,
  input[type="file"],
  input[type="text"] {
    width: 100%;
  }
  .add-form-row {
    flex-direction: column;
    align-items: stretch;
  }
  .add-form-row input,
  .add-form-row select,
  .add-form-row button {
    width: 100%;
    margin-bottom: 10px;
  }
  .manage-item {
    flex-direction: column;
    align-items: flex-start;
  }
  .manage-item .actions {
    margin-top: 10px;
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
  .manage-item .actions button {
    margin-left: 5px;
    margin-right: 0;
  }
  .manage-tabs button {
    flex: 1;
  }
}
</style>